package com.ss.web.tagmark.init;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;

/**
 * 实体类通用验证接口
 *
 * @author Administrator
 *
 */
public class EntityValidator implements org.springframework.validation.Validator {
	protected Logger logger = LoggerFactory.getLogger(EntityValidator.class);
	private Validator validator;

	public EntityValidator(Validator validator) {
		this.validator = validator;
		if (this.validator == null) {
			ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
			validator = factory.getValidator();
		}
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	public void validate(Object target, Errors errors) {
		try {
			Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target);
			if (constraintViolations != null && constraintViolations.size() > 0) {
				for (ConstraintViolation<Object> c : constraintViolations) {
					if (c == null) {
						continue;
					}
					errors.rejectValue(c.getPropertyPath().toString(), c.getMessageTemplate(), c.getExecutableParameters(), c.getMessage());
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
}
